package registe_router_handle

import (
	"github.com/kataras/iris/v12"
	"goServer/models"
)

// return json model part
type PersonInfo struct {
	/*
		Name     string `gorm:"type:varchar(20);not null;"`
			Age      int    `gorm:"type:int(3);not null;"`
			Sex      string `gorm:"type:varchar(10);not null;"`
			Phone    string `gorm:"type:varchar(20);not null;"`
			Grade    string `gorm:"type:varchar(20);not null;"`
			LogoPath string `gorm:"type:varchar(20);not null;"`

		rewrite this to json model
	*/
	Name     string `json:"name"`
	Age      int    `json:"age"`
	Sex      string `json:"sex"`
	Phone    string `json:"phone"`
	Grade    string `json:"grade"`
	LogoPath string `json:"logo_path"`
}

type PostReturn struct {
	Success bool   `json:"success"`
	Info    string `json:"info"`
}

// init part
func Init_PersonInfo() {

	// GET localhost:8080/personinfo?openid=xxx
	// 给定openid，返回个人信息
	RouterHandles = append(RouterHandles, RouterHandle{
		Method: "GET",
		Router: "/personinfo",
		Handler: func(ctx iris.Context) {
			openid := ctx.URLParam("openid")

			res := personFindAll(openid)

			ctx.ContentType("application/json")
			ctx.JSON(res)
		},
	})

	// POST localhost:8080/personinfo
	// POST给定个人信息json，将其写入数据库,返回状态信号
	RouterHandles = append(RouterHandles, RouterHandle{
		Method: "POST",
		Router: "/personinfo",
		Handler: func(ctx iris.Context) {
			ret := PostReturn{Success: true, Info: "success"}

			//writePersonInfo(ctx)
			var personInfo PersonInfo
			ctx.ReadJSON(&personInfo)

			// write to database
			db, err := models.GetDBOnly()
			if err != nil {
				ret.Success = false
				ret.Info = err.Error()
				ctx.JSON(ret)
				return
			}

			var personModel models.Students
			// 将personInfo转换为personModel
			personModel.Name = personInfo.Name
			personModel.Age = personInfo.Age
			personModel.Sex = personInfo.Sex
			personModel.Phone = personInfo.Phone
			personModel.Grade = personInfo.Grade
			personModel.LogoPath = personInfo.LogoPath

			// 将personModel写入数据库
			db.Create(&personModel)

			ctx.JSON(ret)
		},
	})
}

// deal data part (return json model)
func personFindAll(openid string) PersonInfo {
	db, err := models.GetDBOnly()
	if err != nil {
		panic(err)
	}

	var personInfo PersonInfo
	db.Where("wx_id = ?", openid).First(&personInfo)

	return personInfo
}
